package hello.word.m2.maven.support;

//import lombok.NonNull;
//import lombok.Value;

import javax.annotation.Nullable;
import java.util.Objects;
import java.util.Optional;
import java.util.StringJoiner;

//@Value
public class DaoCondition implements Condition {
	/*@NonNull*/
	private final String columnName;
	/*@NonNull*/
	private final String operand;

	private final Object value;

	public DaoCondition(/*@NonNull*/ String columnName, String operand, Object value) {
		this.columnName = columnName;
		this.operand = operand;
		this.value = value;
	}

	@Override
	public Optional<String> asString() {
		return Optional
				.ofNullable(new StringJoiner(" ").add(columnName).add(operand).add(getValueAsString()).toString());
	}

	@Override
	public String toString() {
		return asString().get();
	}

	private String getValueAsString() {
		// TODO:: add converters
		if (value instanceof Number) {
			return Objects.toString(value);
		}
		return "'" + Objects.toString(value, "null") + "'";
	}

	public static Condition like(/*@NonNull*/ String columnName, /*@NonNull*/ String value) {
		return new DaoCondition(columnName, "like", "%" + value + "%");
	}

	public static Condition gt(/*@NonNull*/ String columnName, /*@NonNull*/ Object value) {
		return new DaoCondition(columnName, ">", value);
	}

	public static Condition lt(/*@NonNull*/ String columnName, /*@NonNull*/ Object value) {
		return new DaoCondition(columnName, "<", value);
	}

	public static Condition gte(/*@NonNull*/ String columnName, /*@NonNull*/ Object value) {
		return new DaoCondition(columnName, ">=", value);
	}

	public static Condition lte(/*@NonNull*/ String columnName, /*@NonNull*/ Object value) {
		return new DaoCondition(columnName, "<=", value);
	}

	public static Condition equal(/*@NonNull*/ String columnName, @Nullable Object value) {
		if (value == null || (value instanceof String && "null".equalsIgnoreCase((String) value))) {
			return isNull(columnName);
		}
		return new DaoCondition(columnName, "=", value);
	}

	public static Condition isNull(/*@NonNull*/ String columnName) {
		return new DaoCondition(columnName, "is", null);
	}
}